import os
import shutil
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
from PIL import Image, ImageTk

class TemplateTreeView:
    def __init__(self, root, templates_dir):
        self.root = root
        self.templates_dir = templates_dir
        self.setup_tree()

    def setup_tree(self):
        """设置树形控件"""
        self.tree = ttk.Treeview(self.root)
        self.tree.pack(fill='both', expand=True)
        
        # 绑定事件
        self.tree.bind('<<TreeviewSelect>>', self.on_tree_select)
        self.tree.bind('<ButtonPress-1>', self.on_tree_press)
        self.tree.bind('<B1-Motion>', self.on_tree_motion)
        self.tree.bind('<ButtonRelease-1>', self.on_tree_release)
        self.tree.bind('<Double-1>', self.on_item_double_click)
        self.tree.bind('<F2>', self.on_item_f2)

        self.refresh_tree()

    def on_tree_select(self, event):
        """处理树形控件的选择事件"""
        selected = self.tree.selection()
        if selected:
            self.current_selected_item = selected[0]
            item = self.tree.item(selected[0])
            self.current_selected_text = item['text']
        else:
            self.current_selected_item = None
            self.current_selected_text = None

    def refresh_tree(self):
        """刷新树形结构"""
        for item in self.tree.get_children():
            self.tree.delete(item)

        self.root_node = self.tree.insert('', 'end', text='模板目录', open=True)

        if os.path.exists(self.templates_dir):
            self._load_directory(self.templates_dir, self.root_node)

    def _load_directory(self, path, parent):
        """递归加载目录内容"""
        for item in os.listdir(path):
            item_path = os.path.join(path, item)
            if os.path.isdir(item_path):
                node = self.tree.insert(parent, 'end', text=item, open=False)
                self._load_directory(item_path, node)

    def start_rename(self, item):
        """开始重命名操作"""
        if not item:
            return

        old_name = self.tree.item(item, 'text')
        bbox = self.tree.bbox(item)
        if not bbox:
            return

        entry = ttk.Entry(self.tree)
        entry.insert(0, old_name)
        entry.select_range(0, tk.END)

        def on_entry_done(event=None):
            new_name = entry.get().strip()
            entry.destroy()
            if new_name and new_name != old_name:
                try:
                    old_path = self._get_full_path(item)
                    new_path = os.path.join(os.path.dirname(old_path), new_name)
                    if os.path.exists(new_path):
                        messagebox.showerror("错误", "该名称已存在")
                        return
                    os.rename(old_path, new_path)
                    self.tree.item(item, text=new_name)
                except Exception as e:
                    messagebox.showerror("错误", f"重命名失败：{str(e)}")

        entry.bind('<Return>', on_entry_done)
        entry.bind('<Escape>', lambda e: entry.destroy())
        entry.bind('<FocusOut>', lambda e: entry.destroy())

        entry.place(x=bbox[0], y=bbox[1], width=bbox[2], height=bbox[3])
        entry.focus_set()

    def on_item_double_click(self, event):
        """处理双击事件"""
        item = self.tree.identify('item', event.x, event.y)
        if item:
            self.start_rename(item)

    def on_item_f2(self, event):
        """处理F2按键事件"""
        selected = self.tree.selection()
        if selected:
            self.start_rename(selected[0])

    def create_directory(self):
        """创建新目录"""
        selected = self.tree.selection()
        if not selected:
            return

        new_dir = simpledialog.askstring("新建目录", "请输入目录名称：")
        if new_dir:
            try:
                parent_path = self._get_full_path(selected[0])
                new_path = os.path.join(parent_path, new_dir)
                os.makedirs(new_path)
                self.tree.insert(selected[0], 'end', text=new_dir, open=True)
            except Exception as e:
                messagebox.showerror("错误", f"创建目录失败：{str(e)}")

    def _get_full_path(self, item):
        """获取项目的完整路径"""
        path_parts = []
        while item:
            if self.tree.item(item, 'text') != '模板目录':
                path_parts.insert(0, self.tree.item(item, 'text'))
            item = self.tree.parent(item)
        return os.path.join(self.templates_dir, *path_parts)

    def on_tree_press(self, event):
        """处理鼠标按下事件"""
        item = self.tree.identify('item', event.x, event.y)
        if item:
            self.tree.selection_set(item)
            self._drag_data = {'item': item, 'x': event.x, 'y': event.y}
        else:
            self._drag_data = None

    def on_tree_motion(self, event):
        """处理鼠标移动事件"""
        if hasattr(self, '_drag_data') and self._drag_data:
            pass

    def on_tree_release(self, event):
        """处理鼠标释放事件"""
        if not hasattr(self, '_drag_data') or not self._drag_data:
            return

        target = self.tree.identify('item', event.x, event.y)
        if target and self._drag_data['item'] != target:
            try:
                src_path = self._get_full_path(self._drag_data['item'])
                dst_path = os.path.join(self._get_full_path(target), 
                                      os.path.basename(src_path))
                shutil.move(src_path, dst_path)
                self.tree.move(self._drag_data['item'], target, 'end')
            except Exception as e:
                messagebox.showerror("错误", f"移动失败：{str(e)}")

        self._drag_data = None